﻿/*----------------------------------------------------------------
  //Copyright (C) 2012 赵国伟
  //文件名：OrdersManage.cs
  //文件功能描述：订单管理
  //创建人：赵国伟
  //生成时间：2012/03/17 16:15:00
//----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Shopping.Common;
using Shopping.Model;
using Shopping.DAL;

namespace Shopping.BLL
{
    public class OrdersManage
    {

        private readonly DALOrders dalOrder = new DALOrders();
        private readonly DALOrderLines dalLine = new DALOrderLines();
        private readonly DALOrderProcess dalProcess = new DALOrderProcess();

        #region "查询一条指定的订单信息 by 赵国伟 2012-04-18"
        /// <summary>
        /// 查询一条指定的订单信息
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public OrderInfo GetOrder(int orderId)
        {
            Orders s = dalOrder.GetModel(orderId);
            OrderInfo t = new OrderInfo();
            t.Order = null;
            t.Lines = null;
            t.UserName = null;
            if (s != null)
            {
                t.Order = s;
                t.UserName = DALHelper.GetFieldValue<Users>(s.UserID, UsersEnum.UserName.ToString());
                List<OrderLines> ols = dalLine.QueryList("OrderID=" + orderId, "OrderLineID");
                t.Lines = new List<OrderLineInfo>();
                DALGoodsPictures dalPicture = new DALGoodsPictures();
                Dictionary<int, string> dictGoodsName = BLLHelper.GenerateToHash<Goods>("GoodsID in (Select GoodsID From OrderLines Where OrderID=" + orderId + ")", GoodsEnum.GoodsName);
                Dictionary<int, string> dictGoodsPic = dalPicture.QueryMajorPictureToHash("GoodsID in (select GoodsID from orderlines where OrderID=" + orderId + ")", GoodsPicturesEnum.SuperSmallPictureUrl);
                Dictionary<int, string> dictPack = DictionariesManage.GetDictionariesToHash(DictionaryCategory.包装类型);
                ProvinceCityAreasManage bllArea = new ProvinceCityAreasManage();
                t.Area = bllArea.GetArea(s.AreaID);
                foreach (OrderLines ol in ols)
                {
                    OrderLineInfo l = new OrderLineInfo();
                    l.LineInfo = ol;
                    l.GoodsName = dictGoodsName[ol.GoodsID];
                    l.PackName = dictPack[ol.PackUnitID];
                    if (dictGoodsPic.ContainsKey(ol.GoodsID))
                        l.SuperSmallPictureUrl = dictGoodsPic[ol.GoodsID];
                    t.Lines.Add(l);
                }
            }
            return t;
        }
        #endregion

        #region "保存一条订单信息； by 赵国伟 2012-04-18"
        /// <summary>
        /// 保存一条订单信息；
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public ReturnValue SaveOrder(OrderInfo o)
        {
            ReturnValue ret = new ReturnValue();
           
            o.Order.TotalAmount = o.Order.SendFee-o.Order.CouponMoney;
            foreach (OrderLineInfo l in o.Lines)
            {
                o.Order.TotalAmount += (l.LineInfo.Price * l.LineInfo.Discount * l.LineInfo.Quantity);
            }
            o.Order.TotalAmount = Math.Round(o.Order.TotalAmount, 2);
            if (o.Order.TotalAmount < 0)
                o.Order.TotalAmount = 0;

            Orders old = null;
            if (o.Order.OrderID > 0)
            {
                old = dalOrder.GetModel(o.Order.OrderID);
                o.Order.UserID = old.UserID;
                o.Order.CouponSN = old.CouponSN;
                o.Order.CouponMoney = old.CouponMoney;

                if (o.Order.OrderStatus != old.OrderStatus && o.Order.OrderStatus == OrderStatus.等待付款.ToString())
                {
                    ret.Message = "已付款的订单状态不能调整为等待付款！";
                    return ret;
                }

            }
            else
            {
                if (o.Order.UserID <= 0)
                    o.Order.UserID = Config.DianKe123_UserID;
            }
            ret = dalOrder.Save(o, old);
            return ret;
        }
        #endregion

        #region "删除指定的订单； by 赵国伟 2012-04-18"
        /// <summary>
        /// 删除指定的订单；
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public ReturnValue DeleteOrder(int orderId)
        {
            ReturnValue ret = new ReturnValue();
            Orders o = dalOrder.GetModel(orderId);
            if (o == null)
            {
                ret.Message = "您要删除的订单不存在！";
                return ret;
            }
            if (o.OrderStatus != OrderStatus.等待付款.ToString())
            {
                ret.Message = "该订单不允许删除！（只有未付款的订单才可以删除）";
                return ret;
            }

            ret = dalOrder.DeleteOrder(orderId);

            return ret;
        }
        #endregion

        #region "分页查询订单信息；by 赵国伟 2012-04-18"
        /// <summary>
        /// 分页查询订单信息；
        /// </summary>
        /// <param name="q"></param>
        /// <returns></returns>
        public List<OrderInfo> QueryOrderAsPage(QueryOrdersAsPage q)
        {
            string cond = "1=1 ";
            if (!string.IsNullOrEmpty(q.OrderID))
                cond += " and OrderID like '%" + q.OrderID + "%' ";

            if (!string.IsNullOrEmpty(q.StartDate))
                cond += " and OrderDate >='" + q.StartDate + "' ";
            if (!string.IsNullOrEmpty(q.EndDate))
                cond += " and OrderDate <='" + q.EndDate + " 23:59:59.999' ";

            if (q.UserID > 0)
                cond += " and UserID=" + q.UserID;

            if (!string.IsNullOrEmpty(q.UserName))
                cond += " and UserID in(Select UserID from Users WHere UserName like '%" + q.UserName + "%')";
            if (!string.IsNullOrEmpty(q.OrderStatus))
                cond += " and OrderStatus='" + q.OrderStatus + "' ";

            if (!string.IsNullOrEmpty(q.PayMode))
                cond += " and PayMode ='" + q.PayMode + "' ";

            if (!string.IsNullOrEmpty(q.SendMode))
                cond += " and SendMode = '" + q.SendMode + "' ";

            string orderby = GetOrderBy(q.Sorts);

            List<Orders> listOfSource = dalOrder.QueryListAsPage(cond, orderby, q.CurPage, q.PageSize, out q.TotalCount);
            List<OrderInfo> listOfTarget = null;
            if (listOfSource != null)
            {
                listOfTarget = new List<OrderInfo>();
                Dictionary<int, string> dictUsers = BLLHelper.GenerateToHash<Users>("UserID in(Select UserID From Orders Where " + cond + ")", UsersEnum.UserName);
                DALOrderLines linesDal = new DALOrderLines();
                DALGoodsPictures dalPicture = new DALGoodsPictures();
                foreach (Orders s in listOfSource)
                {
                    OrderInfo t = new OrderInfo();
                    t.Order = s;
                    t.UserName = dictUsers[s.UserID];
                    t.Lines = new List<OrderLineInfo>();
                    var orderlines = linesDal.QueryList(0, " orderid=" + s.OrderID, "");
                    Dictionary<int, string> dictGoods = BLLHelper.GenerateToHash<Goods>("goodsID in (select GoodsID from orderlines where orderid  in(Select OrderID From Orders Where " + cond + "))", GoodsEnum.GoodsName);

                    Dictionary<int, string> dictGoodsPic = dalPicture.QueryMajorPictureToHash("GoodsID in (select GoodsID from orderlines where orderid  in(Select OrderID From Orders Where " + cond + "))", GoodsPicturesEnum.SuperSmallPictureUrl);
                    foreach (OrderLines line in orderlines)
                    {
                        if (!dictGoods.ContainsKey(line.GoodsID))
                            continue;
                        var ol = new OrderLineInfo();
                        ol.LineInfo = line;
                        ol.GoodsName = dictGoods[line.GoodsID];
                        if (dictGoods.ContainsKey(line.GoodsID))
                            ol.SuperSmallPictureUrl = dictGoodsPic[line.GoodsID];
                        t.Lines.Add(ol);
                    }
                    listOfTarget.Add(t);
                }

            }
            return listOfTarget;
        }
        #endregion

        #region "返回指定的排序语句 by 赵国伟  2012-04-18"
        /// <summary>
        /// 返回指定的排序语句
        /// </summary>
        /// <param name="sorts"></param>
        /// <returns></returns>
        public string GetOrderBy(int sorts)
        {
            string orderby = "OrderID desc";
            switch (sorts)
            {
                case 1:
                    orderby = "OrderID ";
                    break;
                case 2:
                    orderby = "TotalAmount desc,OrderID desc";
                    break;
                case 3:
                    orderby = "TotalAmount asc,OrderID desc";
                    break;
            }
            return orderby;
        }
        #endregion

        #region "调整订单状态； by 赵国伟 2012-08-20"
        /// <summary>
        /// 调整订单状态；
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public ReturnValue ModifyStatus(int userId, int orderId, OrderStatus status)
        {
            return dalOrder.ModifyStatus(userId, orderId, status);
        }
        #endregion



    }
}
